package su.product.module;

/**
 * 原料管理
 */
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.kuakao.core.dto.PagerDTO;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import su.product.entity.Cate;
import su.product.entity.Material;
import su.product.service.CateService;
import su.product.service.MaterialService;
import su.tool.RegexUtil;
import su.tool.SuIntUtils;
@Controller
@RequestMapping("/admin/material")
public class MaterialServlet {

	@Autowired
	private CateService cateService;
	
	@Autowired
	private MaterialService materialService;

	protected final Log log = LogFactory.getLog(getClass());
	/**
	 * 首页
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("material_index")
	public String materialIndex(HttpServletRequest request, Model model){
		return "/maintain/product/material_index";
	}
	/**
	 * 分类下的原料列表
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("getMaterialsByCate")
	public String getMaterialsByCate(HttpServletRequest request,PagerDTO s, Model model){
		
		String cateIdStr = request.getParameter("cateId");
		if(StringUtils.isBlank(cateIdStr)){
			model.addAttribute("errorCode", "要查看原料列表，请先选择一个分类");
			return "su_error";
		}
		s.setS3(cateIdStr);
		List<Material> list = materialService.getMaterialsByCate(s);
		model.addAttribute("list", list);
		model.addAttribute("_page", s);
		model.addAttribute("cateid", cateIdStr);
		
		return "/maintain/product/material_list";
	}
	/**
	 * 根据id或简拼得到原料列表
	 * @param request
	 * @param response
	 * @param model
	 */
	@RequestMapping("search_material")
	public void searchMaterial(HttpServletRequest request,HttpServletResponse response, Model model){
		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
        PrintWriter writer = null;
		try {
			writer = response.getWriter();
		} catch (IOException e) {
			log.error(e.getMessage());
		}
		if(writer == null)return;
		
		String q = request.getParameter("term");
		if(StringUtils.isBlank(q) || q.length()>6){//查询条件为空或字符数大于6(显示的汉字)时不予查询
			writer.print("");
			writer.flush();
			writer.close();
			return;
		}
		//System.out.println("aa==="+q);
		List list = new ArrayList();
		Map<String ,String> map;
		PagerDTO dto = new PagerDTO();
		//
		if(RegexUtil.isNumeric(q)){//id
			dto.setS1(q);
		}else{//简拼
			dto.setS2(q);
		}
		List<Material> mList = materialService.getMaterialsByCate(dto);
		if(mList!=null && !mList.isEmpty()){
			for(Material m : mList){
				map=new HashMap<String, String>();
				map.put("id", m.getId()+"");
				map.put("label", m.getMname());
				list.add(map);
			}
		}

		writer.print(JSONArray.fromObject(list.toArray()).toString());
		writer.flush();
		writer.close();
    }
	/**
	 * 原料详情
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("material_detail")
	public String materialDetail(HttpServletRequest request, Model model) {
        int id = SuIntUtils.getInt(request.getParameter("id"));
        if(id==0){
        	model.addAttribute("errorCode", "请选择原料");
        	return "su_error";
        }
        //基本信息
        Material material = materialService.getMaterialById(id);
        model.addAttribute("baseinfo", material);
        //所属分类
        Cate cate = cateService.getById(material.getCateid());
        model.addAttribute("cateInfo", cate);
		return "/maintain/product/material_detail";
	}
	/**
	 * 到 添加/编辑 原料信息页面
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("to_edit_material")
	public String toEditMaterial(HttpServletRequest request, Model model) {
        int id = SuIntUtils.getInt(request.getParameter("id"));
        if(id>0){
        	Material material = materialService.getMaterialById(id);
            model.addAttribute("baseinfo", material);
        }
        model.addAttribute("cateid", request.getParameter("cateid"));
		return "/maintain/product/material_edit";
	}

	/**
	 * 添加一个原料
	 * @param request
	 * @param response
	 * @param cate
	 * @param model
	 */
	@RequestMapping("do_save_material")
	public String doSaveMaterial(HttpServletRequest request,HttpServletResponse response,Material material, Model model){
		String res = "";
		try {
			materialService.saveMaterial(material);
		} catch (Exception e) {
			log.error(e.getMessage());
			res = e.getMessage();
		}
		if(StringUtils.isNotBlank(res)){
			request.setAttribute("errorCode", res);
			return "su_error";
		}
		return "redirect:/admin/material/getMaterialsByCate.action?cateId="+material.getCateid();
	}
	/**
	 * 删除
	 * @param request
	 * @param response
	 * @param model
	 */
	@RequestMapping("do_remove")
	public void doRemove(HttpServletRequest request,HttpServletResponse response, Model model){
		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
        PrintWriter writer = null;
		try {
			writer = response.getWriter();
		} catch (IOException e) {
			log.error(e.getMessage());
		}
		if(writer==null)return;
		Map<String,String> msgs = new HashMap<String,String>();
		
		int id = SuIntUtils.getInt(request.getParameter("id"));
		
		if(id==0){
			msgs.put("no id", "请选择要删除的数据");
		}else{
			String msg = "";
			try {
				materialService.removeMaterial(id);
			} catch (Exception e) {
				log.error(e.getMessage());
				msg = e.getMessage();
			}
			
			if(StringUtils.isNotBlank(msg)){
				msgs.put("service error", msg);
			}else{
				msgs.put("success", "success");
			}
		}
		
		writer.print(JSONObject.fromObject(msgs));
		writer.flush();
		writer.close();
    }
	
}
